package cn.liukuan.jps.utils;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtField;
import javassist.NotFoundException;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.IOException;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by liukuan on 16/5/29.
 */
public class IndexUtils {

    public static ReentrantLock lock = new ReentrantLock();

    public static void indexData(String path, String title, String content) throws IOException {

        lock.lock();

        try {

//            String indexpath = PropertiesUtils.getProp("indexpath");

//            Directory dir = FSDirectory.open(Paths.get(indexpath));

            Directory dir = new RAMDirectory();


            Analyzer analyzer = new IKAnalyzer();
            IndexWriterConfig iwc = new IndexWriterConfig(analyzer);

            iwc.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);

            IndexWriter indexWriter = new IndexWriter(dir, iwc);

            Document doc = new Document();

            Field fieldpath = new StoredField("path", path);
            Field fieldtitle = new TextField("title", title, Field.Store.YES);
            Field fieldcontent = new TextField("content", title, Field.Store.NO);


            doc.add(fieldpath);
            doc.add(fieldtitle);
            doc.add(fieldcontent);

            indexWriter.addDocument(doc);

            indexWriter.commit();

            indexWriter.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }


}
